import React, { useEffect, useState } from 'react'
import { Button, Form, Input, message, Modal, notification, Space, Typography } from 'antd'
import useGetTableData from '@/hooks/useGetTableData'
import SearchForm from '@/components/CustomForm/SearchForm'
import { useForm } from 'antd/es/form/Form'
import PageContainer from '@/components/PageContainer'
import { useTemplate } from '../columns'
import CustomTable from '@/components/CustomTable'
import { getProductTemplateList, productTemplateSave } from '@/api/goods'
import { PlusOutlined } from '@ant-design/icons'
import { onValuesChange } from '@/utils/onValuesChange'
import { ProductTemplateVO } from '../types'
import { EditFormInline, EditFormVertical } from '@/components/CustomForm'
import { useTemplateForm } from '../useForm'
import './index.less'
import PermissionButton from '@/components/PermissionButton'
import { useAppSelector } from '@/store/hooks'
const Index: React.FC = () => {
  const [form] = useForm()
  const [FormTemplate] = useForm()
  const [isModalShow, setisModalShow] = useState<boolean>(false)
  const [exportLoading, setexportLoading] = useState(false)
  const buttonCodeList = useAppSelector((state) => state.login.buttonCodeList) || []
  const [productTemplateId, setproductTemplateId] = useState<null | number>(null)
  const { tableProps, params, setParams, search, reset } = useGetTableData<ProductTemplateVO>(getProductTemplateList, {
    form: form,
  })
  const dataMap: Record<string, string> = {
    productSeries: '商品系列',
    baseSizeCode: '基码',
    patternType: '版型',
    collarType: '领型',
    flowerType: '花型',
    moduleType: '杯型',
    laterThan: '后比',
    moldCupMaterial: '模杯材质',
    moldCupThickness: '模杯厚度',
    moldCupShape: '模杯形状',
    breasted: '排扣',
    fabricType: '面料',
    functionType: '功能',
    styleCode: '风格',
    patternLayoutCode: '图案布局',
    elementCode: '元素',
    technicsCode: '工艺',
    sellTempCode: '适卖温度',
    gramWeight: '克重',
    thicknessCode: '厚度',
    priceTagCode: '价格带',
    ageCode: '年龄段',
  }
  const [initValue, setinitValue] = useState<Record<string, 1>>()
  useEffect(() => {
    const initValue: Record<string, 1> = {}
    for (const key in dataMap) {
      initValue[key] = 1
    }
    setinitValue(initValue)
  }, [])
  const onModalCancel = () => {
    setisModalShow(false)
    FormTemplate.resetFields()
    setproductTemplateId(null)
  }
  const onConfirm = async () => {
    const data = await FormTemplate.validateFields()
    setexportLoading(true)
    const { productTemplateName, ...resetKey } = data
    const notRequired: string[] = []
    const required: string[] = []
    const notShow: string[] = []
    Object.keys(resetKey).forEach((key) => {
      if (resetKey[key] === 1) {
        notRequired.push(key)
      }
      if (resetKey[key] === 2) {
        required.push(key)
      }
      if (resetKey[key] === 3) {
        notShow.push(key)
      }
    })
    const res = await productTemplateSave({
      productTemplateName,
      notRequired,
      required,
      notShow,
      productTemplateId,
    }).finally(() => setexportLoading(false))
    if (res.code == 200) {
      message.success('操作成功')
      search(params)
      onModalCancel()
    }
    if (res.code === 820000 && res.failInfo == null) {
      notification.open({
        type: 'warning',
        message: res.msg,
      })
    }
  }
  const onEditTemplate = (info: ProductTemplateVO) => {
    setproductTemplateId(info.productTemplateId)
    const paramsData: Record<string, any> = {
      productTemplateName: info?.productTemplateName,
    }
    info?.notRequired?.forEach((item) => (paramsData[item] = 1))
    info?.required?.forEach((item) => (paramsData[item] = 2))
    info?.notShow?.forEach((item) => (paramsData[item] = 3))
    FormTemplate.setFieldsValue(paramsData)
    setisModalShow(true)
  }
  return (
    <PageContainer className="goods_goodsInfoTemplate_page">
      <SearchForm
        className="goodsInfoTemplateDom"
        params={params}
        form={form}
        onValuesChange={(changedValues) => onValuesChange(changedValues, ['productTemplateName'], form)}
        extra={
          <div className="table_extra_flex">
            <PermissionButton
              permission="goodsInfoTemplateCreate"
              type="primary"
              icon={<PlusOutlined />}
              onClick={() => {
                setproductTemplateId(null)
                setisModalShow(true)
              }}
            >
              新建模板
            </PermissionButton>
          </div>
        }
        searchConfig={[
          {
            name: 'productTemplateName',
            label: '模板名称',
            type: 'Input',
          },
        ]}
        onFinish={(vals: any) => {
          search({
            ...vals,
          })
        }}
        onReset={() => {
          reset()
        }}
      ></SearchForm>
      <CustomTable
        bordered
        columns={useTemplate(onEditTemplate, buttonCodeList.includes('goodsInfoTemplateEdit'))}
        {...tableProps}
        rowKey={(rows) => rows.productTemplateId}
        extraHeight={28}
        isScrollY
        filterDomClassName="goodsInfoTemplateDom"
      />

      <Modal
        title="新建模板"
        width={1300}
        open={isModalShow}
        maskClosable
        onCancel={onModalCancel}
        footer={
          <div className="flex_end">
            <Space>
              <Button onClick={onModalCancel}>取消</Button>
              <Button
                type="primary"
                onClick={() => FormTemplate.validateFields().then(onConfirm)}
                loading={exportLoading}
              >
                确定
              </Button>
            </Space>
          </div>
        }
      >
        <div className="goods_info_template_form_wrap">
          <Form form={FormTemplate}>
            <Form.Item
              label="模板名称"
              name="productTemplateName"
              rules={[{ required: true, message: '请输入模板名称' }]}
            >
              <Input style={{ maxWidth: 220 }}></Input>
            </Form.Item>
          </Form>
        </div>
        <EditFormInline
          editConfig={useTemplateForm(dataMap)}
          form={FormTemplate}
          initialValues={{ ...initValue }}
        ></EditFormInline>
      </Modal>
    </PageContainer>
  )
}

export default Index
